package com.dong.binaryTree;

import java.util.LinkedList;

/**
 * @Classname isSymmetric
 * @Description 对称二叉树
 * @Date 2022/4/8 11:03
 * @Author dcz
 */
public class isSymmetric {
    public boolean isSymmetric(TreeNode root) {
        LinkedList<TreeNode> deque = new LinkedList<>();
        deque.offer(root.left);
        deque.offer(root.right);
        while (!deque.isEmpty()){
            TreeNode leftNode = deque.poll();
            TreeNode rightNode = deque.poll();
            if(leftNode==null && rightNode==null){
                continue;
            }
            if (leftNode==null || rightNode==null || rightNode.val!=leftNode.val){
                return false;
            }
            deque.offer(leftNode.left);
            deque.offer(rightNode.right);
            deque.offer(leftNode.right);
            deque.offer(rightNode.left);
        }
        return true;

    }

    /**
     * 递归法
     */
    public boolean isSymmetric1(TreeNode root) {
        return compare(root.left, root.right);
    }

    private boolean compare(TreeNode left, TreeNode right) {
        if (left == null && right != null) {
            return false;
        }

        if (left != null && right == null) {
            return false;
        }

        if (left == null && right == null) {
            return true;
        }
        if (left.val != right.val) {
            return false;
        }
        // 比较外侧
        boolean compareOutside = compare(left.left, right.right);
        // 比较内侧
        boolean compareInside = compare(left.right, right.left);
        return compareOutside && compareInside;
    }

}
